//
//  Converter.m
//  DocConvert
//
//  Created by 克里斯龙 on 2024/8/16.
//

#import "Converter.h"
#import <AFNetworking.h>
#define ApiKey @"02b0271a3bec97e266596ec949b33fa7"
@implementation Converter
- (void)convertFileAtPath:(NSString *)filePath
               outputFormat:(NSString *)outputFormat
               completion:(void (^)(NSString *outputFilePath, NSError *error))completion {
    
    // Convertio API的URL
    NSString *urlString = @"https://api.convertio.co/convert";
    NSURL *url = [NSURL URLWithString:urlString];
    
    // 创建HTTP请求
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
//    [manager.requestSerializer setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
//    [manager.requestSerializer setValue:[NSString stringWithFormat:@"Bearer %@", ApiKey] forHTTPHeaderField:@"Authorization"];

      manager.responseSerializer = [AFJSONResponseSerializer serializer];
     manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json", @"text/javascript",@"text/html",@"text/plain",nil];

    // Convertio API的API密钥
    NSString *apiKey = ApiKey;
    
    // 设置请求参数
    NSDictionary *parameters = @{
        @"apikey": apiKey,
        @"input": @"upload",
        @"file": @"/Users/kelisilong/Desktop/DocConvert/DocConvert/pdfTest.docx",
        @"filename":[filePath lastPathComponent],
        @"outputformat": outputFormat
    };
    
    // 发起POST请求
 
//    
    [manager POST:urlString parameters:parameters headers:nil progress:^(NSProgress * _Nonnull uploadProgress) {

    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        // 获取任务ID
        NSString *jobId = responseObject[@"id"];

        // 检查任务状态
     } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        completion(nil, error);
    }];
//    
    
    
    
    
 
    // 发送POST请求
//    [manager POST:urlString parameters:parameters headers:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
//        
//        // 将文件附加到请求体中
//        NSData *fileData = [NSData dataWithContentsOfFile:filePath];
//        NSString *fileName = [filePath lastPathComponent];
//        [formData appendPartWithFileData:fileData name:@"file" fileName:fileName mimeType:@"application/x-www-form-urlencoded"];
//        
//    } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//        
//        // 处理成功响应
//        NSString *conversionId = responseObject[@"data"][@"id"];
//        [self checkConversionStatus:conversionId completion:completion];
//        
//    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//        // 处理失败响应
//        if (completion) {
//            completion(nil, error);
//        }
//    }];
}

- (void)checkConversionStatus:(NSString *)conversionId completion:(void (^)(NSString *outputFilePath, NSError *error))completion {
    
    // 构建查询状态的URL
    NSString *urlString = [NSString stringWithFormat:@"https://api.convertio.co/convert/%@/status", conversionId];
    
    // 创建HTTP请求
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    
    // 发送GET请求
    [manager GET:urlString parameters:nil headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        // 检查转换状态
        NSString *status = responseObject[@"data"][@"status"];
        
        if ([status isEqualToString:@"finished"]) {
            // 转换完成，下载文件
            NSString *outputFileUrl = responseObject[@"data"][@"output"][@"url"];
            [self downloadConvertedFileFromURL:outputFileUrl completion:completion];
        } else if ([status isEqualToString:@"error"]) {
            // 处理转换错误
            if (completion) {
                NSError *error = [NSError errorWithDomain:@"Convertio" code:1001 userInfo:@{NSLocalizedDescriptionKey: @"Conversion failed"}];
                completion(nil, error);
            }
        } else {
            // 等待一段时间后再次查询状态
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self checkConversionStatus:conversionId completion:completion];
            });
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        // 处理失败响应
        if (completion) {
            completion(nil, error);
        }
    }];
}

- (void)downloadConvertedFileFromURL:(NSString *)fileURL completion:(void (^)(NSString *outputFilePath, NSError *error))completion {
    
    // 创建目标文件路径
    NSString *fileName = [fileURL lastPathComponent];
    NSString *outputFilePath = [NSTemporaryDirectory() stringByAppendingPathComponent:fileName];
    
    // 创建HTTP请求
    NSURL *url = [NSURL URLWithString:fileURL];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    // 下载文件
    NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
        return [NSURL fileURLWithPath:outputFilePath];
    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
        if (completion) {
            completion(outputFilePath, error);
        }
    }];
    
    [downloadTask resume];
}
@end
